package com.jt.www.admin.user.controller;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.jt.www.admin.order_pc.service.ExportConfigService;
import com.jt.www.admin.user.service.RegisterCustomerService;
import com.jt.www.domain.dto.RegisterCustomerDTO;
import com.jt.www.domain.enums.common.ExportChannelTypeEnum;
import com.jt.www.domain.po.ExportConfigEntity;
import com.jt.www.domain.vo.PromotersVo;
import com.jt.www.domain.vo.RegisterCustomerVo;
import com.jt.www.model.registerCustomer.RegisterCustomer;
import com.jt.www.model.registerCustomer.vo.*;
import com.jt.www.model.reps.GenericDataResponse;
import com.jt.www.model.reps.GenericListResponse;
import com.jt.www.util.DateUtils;
import com.jt.www.util.JsonUtil;
import com.jt.www.util.excel.CsvExportUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "推广相关接口", tags = {"REGISTER-INFO-API"}, description = "推广相关接口")
@RestController
@RequestMapping(value = "/registerCustomer")
public class RegisterCustomerController {

    public static final Logger log = LoggerFactory.getLogger(RegisterCustomerController.class);

    @Autowired
    private RegisterCustomerService registerCustomerService;
    @Autowired
    private ExportConfigService exportConfigService;

    /**
     * 根据usercode注册指定的用户
     */
    @ApiOperation(value = "用户二维码注册", notes = "用户二维码注册", httpMethod = "POST")
    @PostMapping(value = "/addCustomer", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = "application/json;charset=UTF-8")
    public ResponseEntity insertBinaryRegisterCustomer(@RequestBody RegisterCustomer registerCustomer) {

        String findCode = "insertBinaryRegisterCustomer_" + System.currentTimeMillis();

        return registerCustomerService.insertBinaryRegisterCustomer(findCode, registerCustomer);

    }

    /**
     * 分页查询推广关系 列表
     */
    @ApiOperation(value = "分页查询推广关系", notes = "分页查询推广关系", httpMethod = "POST")
    @PostMapping(value = "/queryCustomers")
    public ResponseEntity<GenericListResponse<RegisterCustomerVo>> queryCustomers(@RequestBody CustomerListParam customerListParam) throws Exception {

        String findCode = "queryCustomerList_" + System.currentTimeMillis();

        log.info("{} 分页查询推广关系 入参：{}", findCode, JsonUtil.object2Json(customerListParam));
        return registerCustomerService.queryCustomers(findCode, customerListParam);
    }

    /**
     * 推广关系列表导出
     *
     * @param response
     * @param customerListParam
     */
    @ApiOperation(value = "推广关系列表导出", notes = "推广关系列表导出")
    @GetMapping(value = "/exportCustomers", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public void exportCustomers(HttpServletResponse response, CustomerListParam customerListParam) {
        String findCode = "exportCustomers_" + System.currentTimeMillis();
        OutputStream os = null;
        try {
            //查询导出配置
            ExportConfigEntity exportConfigEntity = exportConfigService.getExportConfig(ExportChannelTypeEnum.REGISTER_CUSTOMER.getCode());
            if (null == exportConfigEntity) {
                return;
            }
            String fileName = exportConfigEntity.getFileName();

            os = response.getOutputStream();
            CsvExportUtil.responseSetProperties(fileName, response);
            //模板位置
            String titles = exportConfigEntity.getTitles();
            CsvExportUtil.setTitles(titles, os);
            List<RegisterCustomerVo> appList;
            int pn = 1;
            customerListParam.setPn(pn);
            customerListParam.setPs(CsvExportUtil.MAX_PAGE_SIZE);
            String[] keyArr = exportConfigEntity.getKeyArr().split(",");

            //分批查询并生成数据插入到导出文件中
            while (CollectionUtils.isNotEmpty(appList = registerCustomerService.queryCustomers(findCode, customerListParam).getBody().getList())) {
                List list = Lists.transform(appList, (Function<RegisterCustomerVo, Object>) registerCustomerVo -> new RegisterCustomerDTO(registerCustomerVo));
                CsvExportUtil.doExport(list, keyArr, os);
                customerListParam.setPn(++pn);
                if (customerListParam.getPs() > appList.size()) {
                    break;
                }
            }
        } catch (Exception e) {
            log.error("{}导出发生错误:", findCode, e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                }
            }
        }
    }

    @ApiOperation(value = "获取推广人信息", notes = "获取推广人信息", httpMethod = "GET")
    @GetMapping(value = "/queryPromotersInfo", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity<GenericDataResponse<ManagerInfoVo>> queryPromotersInfo(String userCode) {

        String findCode = "queryPromotersInfo_" + System.currentTimeMillis();

        log.info("{} 获取推广人信息 入参：{}", findCode, userCode);

        return registerCustomerService.queryPromotersInfo(findCode, userCode);
    }

    /**
     * 业绩查询（推广）
     */
    @ApiOperation(value = "分页查询业绩查询（推广）信息", notes = "分页查询业绩查询（推广）信息", httpMethod = "POST")
    @PostMapping(value = "/queryAchievementList")
    public ResponseEntity queryAchievementList(@RequestBody AchievementListQo achievementListQo) throws Exception {

        String findCode = "queryAchievementList_" + System.currentTimeMillis();

        log.info("{} 分页查询业绩查询（推广）信息 入参：{}", findCode, JsonUtil.object2Json(achievementListQo));

        return registerCustomerService.queryAchievementList(findCode, achievementListQo);
    }

    /**
     * 业绩查询（推广）导出
     *
     * @param response
     * @param param
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "导出业绩查询（推广）信息", notes = "导出业绩查询（推广）信息", httpMethod = "GET")
    @GetMapping(value = "/exportAchievementList", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public void exportAchievementList(HttpServletResponse response, AchievementExportQo param) throws Exception {

        List<AchievementListVO> list = registerCustomerService.exportAchievementList(param);

        // 构造导出数据结构
        String titles = "序号,推广人所在机构,推广人姓名,推广人账号,被推广人账号,保单号,产品名称,投保日期," +
                "保费金额,投保人姓名,被保险人姓名,被保险人所在地,保险期间";  // 设置表头
        String keys = "serialNo,branchName,promoterName,promoterAccount,offlineAccount,policyNo,productName,applicantDate," +
                "actualPrem,holderName,insuredName,insuredLocation,polDate";  // 设置每列字段

        // 构造导出数据
        List<Map<String, Object>> datas = new ArrayList<>();
        Map<String, Object> map = null;

        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                map = new HashMap<>();
                map.put("serialNo", i + 1);
                map.put("branchName", list.get(i).getBranchName());
                map.put("promoterName", list.get(i).getPromoterName());
                map.put("promoterAccount", list.get(i).getPromoterAccount());
                map.put("offlineAccount", list.get(i).getOfflineAccount());
                map.put("policyNo", list.get(i).getPolicyNo() + "\t");
                map.put("productName", list.get(i).getProductName());
                map.put("applicantDate", DateUtils.format(list.get(i).getApplicantDate(), "yyyy-MM-dd"));
                map.put("actualPrem", list.get(i).getActualPrem());
                map.put("holderName", list.get(i).getHolderName());
                map.put("insuredName", list.get(i).getInsuredName());
                map.put("insuredLocation", list.get(i).getInsuredLocation());
                map.put("polDate", DateUtils.format(list.get(i).getPolStartDate(), "yyyy-MM-dd HH:mm:ss") + " - " + DateUtils.format(list.get(i).getPolEndDate(), "yyyy-MM-dd HH:mm:ss"));

                datas.add(map);
            }
        }

        // 设置导出文件前缀
        String fName = "业绩信息_";

        // 文件导出
        OutputStream os = response.getOutputStream();
        CsvExportUtil.responseSetProperties(fName, response);
        CsvExportUtil.doExport(datas, titles, keys, os);
        os.close();
    }


    /**
     * ****作废接口*****
     * 内部人员配置接口
     * 只在我学保登录时调用，将用户的信息传送过来
     */
    @ApiOperation(value = "内部人员配置接口（作废）", notes = "内部人员配置接口", httpMethod = "POST")
    @PostMapping(value = "/setManager", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = "application/json;charset=UTF-8")
    public ResponseEntity setManager(@RequestBody RegisterCustomer registerCustomer,
                                     @ApiParam(value = "用户等级", required = true) @RequestParam("level") String level) {

        String findCode = "setManager_" + System.currentTimeMillis();

        log.info("{} 内部人员配置接口 入参->{},level->{}", findCode, JsonUtil.object2Json(registerCustomer), level);

        return registerCustomerService.setManager(findCode, registerCustomer, level);

    }

    /**
     * 通过员工编号查询推广人相关信息
     */
    @ApiOperation(value = "通过员工编号查询推广人相关信息", notes = "通过帐号查询推广人", httpMethod = "GET")
    @GetMapping(value = "/queryPromotersByEmployeeNum", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<GenericDataResponse<PromotersVo>> queryPromotersByEmployeeNum(
            @ApiParam(value = "员工编号", required = true) @RequestParam("employeeNum") String employeeNum) {
        if (StringUtils.isBlank(employeeNum)) {
            return GenericDataResponse.errorWithMsg("员工编号不能为空!", PromotersVo.class);
        }
        String findCode = "queryPromotersByEmployeeNum" + System.currentTimeMillis();
        return registerCustomerService.queryPromotersByEmployeeNum(findCode, employeeNum);
    }

    /**
     * 解除推广关系
     */
    @ApiOperation(value = "解除推广关系", notes = "解除推广关系", httpMethod = "GET")
    @GetMapping(value = "/removePromotionById", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity removePromotionById(Integer id) {

        String findCode = "removePromotionById" + System.currentTimeMillis();
        if (registerCustomerService.removePromotionById(findCode, id, false) > 0) {
            return GenericDataResponse.okWithData("已解除!");
        } else {
            return GenericDataResponse.errorWithMsg("解除失败!");
        }
    }

    /**
     * 推广关系转移
     */
    @ApiOperation(value = "推广关系转移", notes = "推广关系转移", httpMethod = "POST")
    @PostMapping(value = "/transferPromotionById", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = "application/json;charset=UTF-8")
    public ResponseEntity transferPromotionById(@RequestBody RegisterCustomer registerCustomer) {

        String findCode = "transferPromotionById_" + System.currentTimeMillis();

        log.info("{} 内部人员配置接口 入参->{}", findCode, JsonUtil.object2Json(registerCustomer));

        return registerCustomerService.transferPromotionById(findCode, registerCustomer);

    }

    @ApiOperation(value = "保单绑定推广人", httpMethod = "POST")
    @PostMapping(value = "/policyAgent", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity policyAgent(@ApiParam(value = "绑定推广人清单", required = true) @RequestParam MultipartFile excelFile) {

        return registerCustomerService.policyAgent(excelFile);
    }

}
